// utils/websocket.js
class WebSocketManager {
  constructor() {
    this.socket = null;
    this.messageHandlers = new Set();
    this.reconnectAttempts = 0;
    this.MAX_RECONNECT_ATTEMPTS = 5;
  }

  async connect(token) {

    // 检查token是否存在
    if (!token) {
      console.warn('没有token，跳过WebSocket连接');
      return Promise.reject(new Error('没有认证token'));
    }

    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      return this.socket;
    }

    return new Promise((resolve, reject) => {
      try {
        // this.socket = new WebSocket(`ws://192.168.6.102:8889/chat?token=${token}`);

        // 正确的地址：使用当前域名
        const getWebSocketUrl = () => {
          const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
          return `${protocol}//${window.location.host}/chat`;
        };
        this.socket = new WebSocket(`${getWebSocketUrl()}?token=${token}`);
        
        this.socket.onopen = () => {
          console.log('WebSocket连接成功');
          this.reconnectAttempts = 0;
          resolve(this.socket);
        };
        
        this.socket.onmessage = (event) => {
          this.handleMessage(event);
        };
        
        this.socket.onclose = (event) => {
          console.log('WebSocket连接关闭');
          this.attemptReconnect(token);
        };
        
        this.socket.onerror = (error) => {
          console.error('WebSocket错误', error);
          reject(error);
        };
      } catch (error) {
        reject(error);
      }
    });
  }

  handleMessage(event) {
    const message = JSON.parse(event.data);
    this.messageHandlers.forEach(handler => {
      try {
        handler(message);
      } catch (error) {
        console.error('消息处理错误', error);
      }
    });
  }

  addMessageHandler(handler) {
    this.messageHandlers.add(handler);
  }

  removeMessageHandler(handler) {
    this.messageHandlers.delete(handler);
  }

  sendMessage(message) {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      console.log('this.socket.value=', this.socket.value);
      this.socket.send(JSON.stringify(message));
      console.log('发送消息：', message);
      return true;
    }
    return false;
  }

  async attemptReconnect(token) {
    if (this.reconnectAttempts >= this.MAX_RECONNECT_ATTEMPTS) {
      console.error('达到最大重连次数');
      return;
    }

    this.reconnectAttempts++;
    const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 10000);
    
    setTimeout(async () => {
      try {
        await this.connect(token);
      } catch (error) {
        console.error('重连失败', error);
      }
    }, delay);
  }
}

export const webSocketManager = new WebSocketManager();